package com.wangsh.forward.web.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangsh.forward.outer.service.IClientOuterService;
import com.wangsh.forward.outer.service.IServerOperOuterService;
import com.wangsh.forward.outer.service.impl.ClientOuterServiceImpl;
import com.wangsh.forward.outer.service.impl.ServerOperOuterServiceImpl;
import com.wangsh.forward.system.pojo.ASysHistory;
import com.wangsh.forward.system.service.ISystemService;
import com.wangsh.forward.system.service.impl.SystemServiceImpl;
import com.wangsh.forward.util.ServiceCallableUtil;
import com.wangsh.webforward.common.pojo.ApiResponse;
import com.wangsh.webforward.common.pojo.ApiResponseEnum;
import com.wangsh.webforward.common.servlet.BaseServlet;
import com.wangsh.webforward.common.util.ConstatFinalUtil;
import com.wangsh.webforward.common.util.ExecutorServiceUtil;
import com.wangsh.webforward.common.util.PageInfoUtil;

/**
 * 系统配置列表
 * 
 * @author TeaBig
 */
public class SystemHeadServlet extends BaseServlet
{
	private static final long serialVersionUID = 1L;
	private IClientOuterService clientOuterService;
	private IServerOperOuterService serverOperOuterService;
	private ISystemService systemService ;

	/**
	 * 初始化对象
	 * @throws ServletException
	 */
	public void initObject()
	{
		if(this.clientOuterService == null)
		{
			this.clientOuterService = new ClientOuterServiceImpl();
		}
		if(this.serverOperOuterService == null)
		{
			this.serverOperOuterService = new ServerOperOuterServiceImpl() ; 
		}
		if(this.systemService == null)
		{
			this.systemService = new SystemServiceImpl() ; 
		}
	}
	
	/**
	 * Servlet的核心方法,不管是Post还是get都要执行此方法
	 */
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		super.service(request, response);
		
		/* 接收一个method参数 */
		String method = request.getParameter("method");
		if ("threadList".equalsIgnoreCase(method))
		{
			this.threadList(request, response);
		} else if ("serverInsert".equalsIgnoreCase(method))
		{
			this.serverInsert(request, response);
		} else if ("serverInsertSubmit".equalsIgnoreCase(method))
		{
			this.serverInsertSubmit(request, response);
		} else if ("serverList".equalsIgnoreCase(method))
		{
			this.serverList(request, response);
		} else if ("uploadOrdersUser".equalsIgnoreCase(method))
		{
			this.uploadOrdersUser(request, response);
		} else if ("uploadOrdersUserSubmit".equalsIgnoreCase(method))
		{
			this.uploadOrdersUserSubmit(request, response);
		} else if ("historyFileList".equalsIgnoreCase(method))
		{
			this.historyFileList(request, response);
		}
	}

	/**
	 * 准备数据,显示一下
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void serverList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==serverList==");
		String path = "/WEB-INF/jsp/head/serverList.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 请求服务器发起提交
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void serverInsertSubmit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==serverInsertSubmit==");
		HttpSession session = request.getSession();
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		String url = request.getParameter("url");
		String json = request.getParameter("json");

		JSONObject reqJSON = new JSONObject();
		if (!"".equalsIgnoreCase(json))
		{
			/* 传了上行参数,解析 */
			try
			{
				reqJSON = (JSONObject) JSON.parse(json);
			} catch (Exception e)
			{
				ConstatFinalUtil.SYS_LOGGER.error("解析上行参数失败了,上行参数:{}", json, e);
				/* 上传的json数据格式不正确 */
				Map<String, String> infoMap = new HashMap<String, String>();
				infoMap.put("info", e.toString());
				// code=10
				apiResponse.setCode(ApiResponseEnum.INFO_JSON_FORMAT_ERROR.getStatus());
				// 上传的json数据格式不正确,信息:${info},("info",e.toString)
				apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), infoMap);
				String responseStr = apiResponse.toJSON().toJSONString();
				/* 输出数据 */
				this.printOut(response, responseStr);
				return;
			}
		}

		apiResponse = this.clientOuterService.clientTaskListService(url, reqJSON);
		session.setAttribute("response", apiResponse.toJSON());
		response.sendRedirect(request.getContextPath() + "/head/system.htm?method=serverList");
	}

	/**
	 * 请求服务器发起攻击
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void serverInsert(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==serverInsert==");
		/* 清除信息 */
		this.clearInfo(request, response,null,"true");
		String path = "/WEB-INF/jsp/head/serverInsert.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 查看多线程列表
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void threadList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==threadList==");
		/* 清除信息 */
		this.clearInfo(request, response,null,"true");
		String path = "/WEB-INF/jsp/head/threadList.jsp";
		request.setAttribute("threadMap", ConstatFinalUtil.THREAD_MAP);
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 进入文件上传页面
	 */
	private void uploadOrdersUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==uploadOrdersUser==");
		Map<String, String> headerMap = new HashMap<String, String>();
		try
		{
			//JSONObject ipLocation = jsoupUtil.ipLocation("", headerMap);
			//System.out.println(ipLocation);
			Map<String, String> paramsMap = new HashMap<String, String>();
			String urlStr = ConstatFinalUtil.CONFIG_JSON.getString("spliderServer.outer.url");
			//准备参数
			JSONObject dataCliReqJSON = new JSONObject();
			dataCliReqJSON.put("version", "1");
			dataCliReqJSON.put("method", "sysCountryList");
			dataCliReqJSON.put("pubKey", "1");
			dataCliReqJSON.put("encrypt", "1");
			dataCliReqJSON.put("data", new JSONObject());
			paramsMap.put("json", dataCliReqJSON.toJSONString());
			Map<String, String> responseMap = new HashMap<String, String>();
			String coutnryResponse = httpUtil.methodPost(urlStr, headerMap, paramsMap, responseMap);
			JSONObject responseJSON = JSON.parseObject(coutnryResponse) ; 
			if(responseJSON != null && responseJSON.getByte("code") == ApiResponseEnum.STATUS_SUCCESS.getStatus())
			{
				JSONArray jsonArray = responseJSON.getJSONObject("data").getJSONArray("list");
				request.setAttribute("responseStr", jsonArray);
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("报错了",e);
		}
		/* 清除信息 */
		this.clearInfo(request, response,null,"false");
		String path = "/WEB-INF/jsp/head/fileUpload.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 文件上传提交
	 */
	private void uploadOrdersUserSubmit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("==uploadOrdersUserSubmit==");
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		
		JSONObject uploadData = serverOperOuterService.uploadOrdersUser(request);
		//判断用户是否传了一个空数据
		if (uploadData.size() !=0 && uploadData !=null)
		{
			serverOperOuterService.writeConfig(uploadData);
			List<Map<String, String>> readFileCsv = poiUtil.readFileCsv(uploadData.getString("path"));
			
			/* 多线程启动 */
			ServiceCallableUtil serviceCallableUtil = new ServiceCallableUtil();
			String operType = "uploadCsvFacebook" ; 
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			paramsMap.put("readFileCsv", readFileCsv);
			paramsMap.put("uploadData", uploadData);
			paramsMap.put("serverOperOuterService", serverOperOuterService);
			/* 设置参数 */
			serviceCallableUtil.setOperType(operType);
			serviceCallableUtil.setParamsMap(paramsMap);
			
			/* 启动多线程 */
			ExecutorServiceUtil.submit(serviceCallableUtil);
			/* 多线程已经启动 */
			apiResponse.setCode(ApiResponseEnum.INFO_THREAD_START.getStatus());
			
			/* 设置提示信息 */
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
			
			/* 存储页面的提示信息 */
			this.setInfo(request, apiResponse);
		}else {
			/* 没有上传文件 */
			apiResponse.setCode(ApiResponseEnum.INFO_UOLOADFILE_NULL.getStatus());
			
			/* 设置提示信息 */
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
			
			/* 存储页面的提示信息 */
			this.setInfo(request, apiResponse);
		}
		/*=====页面跳转=====*/
		String path = "/head/system.htm?method=uploadOrdersUser";
		response.sendRedirect(request.getContextPath() + path);
	}
	
	public void historyFileList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("===historyFileList=====");
		Map<String , Object> condMap = new HashMap<String, Object>();
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		ApiResponse<ASysHistory> apiResponse=this.systemService.findCondListHistoryService(pageInfoUtil, condMap);
		List<ASysHistory> historyList = apiResponse.getDataListJava();
		request.setAttribute("historyList",historyList);
		request.setAttribute("size",historyList.size());
		/* 清除信息 */
		this.clearInfo(request, response,apiResponse,"true");
		
		String path = "/WEB-INF/jsp/head/fileUploadList.jsp";
		request.getRequestDispatcher(path).forward(request, response);
	}
}
